#include "SlaveLoopController.h"

#include "LoopController.h"


SlaveLoopController::SlaveLoopController(const ExtendDeviceType& deviceType, std::uint32_t slaveIndex, const LoopGroupInfo& groupInfo, LoopController& parent) :
    mgroupInfo(groupInfo), mdeviceType(deviceType), mslaveIndex(slaveIndex), mparent(parent) {

    mslaveCommandPrefix.resize(10);
    snprintf(&mslaveCommandPrefix[0], mslaveCommandPrefix.size() + 1, "<SLAVE_%02d_", mslaveIndex);
}



void SlaveLoopController::buildCommandAndSavePhase(const std::string_view& phaseView) {
    mcommandBuilder = mslaveCommandPrefix + "ELECT_";

    char buffer[3];
    snprintf(buffer, sizeof(buffer), "%02d", mgroupInfo.portCount);

    mcommandBuilder.append(buffer, 2);
    for (const char& ch : phaseView) {
        mcommandBuilder.push_back('_');
        mcommandBuilder.push_back(ch);
    }
    mcommandBuilder.push_back('>');

    //CURRENT_PHASE_KEY+ getExtendNum()
}



bool SlaveLoopController::updateInfomation(std::string& result) {
    mparent.mchannel.sendStringReturnString(mcommandBuilder, result);
    return true;
}



void SlaveLoopController::changeAllChannelStatusFunc(const LoopStatus* command, const LoopSize_t& length) {
    //             <CIRCUIT_ON/OFF_DATA_000000000000_00500>
    std::string commandBuilder = mslaveCommandPrefix + "CIRCUIT_ON/OFF_DATA_";
    commandBuilder.append(reinterpret_cast <const char*>(command), length);
    char buffer[8];
    snprintf(buffer, sizeof (buffer), "_%05d>", mparent.mloopControllerConfig.switchInterval);
    commandBuilder.append(buffer, sizeof (buffer) - 1);
    std::string result;

    mparent.mchannel.sendStringReturnString(commandBuilder, result);
//    if (mcommandBuilder != result){
//        throw BUILD_EXCEPTION_MESSAGE(FirmwareError::LOOP_SWITCH_FAILED, result);
//    }
}



void SlaveLoopController::changeSingleChannelStatusFunc(const int& loopIndex, const LoopStatus& status) {
    std::string commandBuilder = mslaveCommandPrefix + "CIRCUIT_ON/OFF_ONE_";
    commandBuilder += BINARY_TO_CHAR(loopIndex);
    commandBuilder += '_';
    commandBuilder += status;
    commandBuilder +=  '>';

    std::string result;
    mparent.mchannel.sendStringReturnString(commandBuilder, result);
}

